package cn.ygyg.bps.bus.starter.repository;

import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @desc：CustomTraceRepository
 * @author: guanliang.xue
 * @date: 2021/5/10 17:33
 * @version:
 * @since:
 */
public class BpsBusEventTraceRepositoryImpl implements BpsBusEventTraceRepository {
    private int capacity = 100;

    private boolean reverse = true;

    private final List<Map<String,Object>> traces = new LinkedList<>();

    /**
     * Flag to say that the repository lists traces in reverse order.
     * @param reverse flag value (default true)
     */
    public void setReverse(boolean reverse) {
        synchronized (this.traces) {
            this.reverse = reverse;
        }
    }

    /**
     * Set the capacity of the in-memory repository.
     * @param capacity the capacity
     */
    public void setCapacity(int capacity) {
        synchronized (this.traces) {
            this.capacity = capacity;
        }
    }

    @Override
    public List<Map<String,Object>> findAll() {
        synchronized (this.traces) {
            return Collections.unmodifiableList(new ArrayList<>(this.traces));
        }
    }

    @Override
    public void add(Map<String,Object> trace) {
        synchronized (this.traces) {
            while (this.traces.size() >= this.capacity) {
                this.traces.remove(this.reverse ? this.capacity - 1 : 0);
            }
            if (this.reverse) {
                this.traces.add(0, trace);
            }
            else {
                this.traces.add(trace);
            }
        }
    }
}
